package Servlet;

import Entity.Friends;
import Entity.Player;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * @author Clara
 */
public class FriendsServlet extends HttpServlet {

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //deferentiate whether you need to search or just get list of freinds
        //if get list
        if(request.getParameter("friendName")==null){
            request.setAttribute("friendslist", getFriends(request.getParameter("userName")));
        }
        //if search
        else{
            request.setAttribute("friendslist", searchFriends(request.getParameter("userName"),request.getParameter("friendName")));
        }
        // Now that the controller has gathered the data from the model,
        // pass the data onto the view to render it as JSON.
        RequestDispatcher view = request.getRequestDispatcher("/friends_view.jsp");
        view.forward(request, response);
    }

    //Get a list of friends of a given username.
    private List<Map<String, String>> getFriends(String userName) {
        List<Map<String, String>> friendsInfo = new ArrayList<Map<String, String>>();

        try {
            //get context from context file.
            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            //query for all friends of a user.
            Query p = em.createNamedQuery("Friends.findByUserName").setParameter("userName", userName);
            List<Friends> results = p.getResultList();
            //build list of strings for result to pass to json
            for (Friends f : results) {
                Map<String, String> friends = new HashMap<String, String>();
                friends.put("friendName", f.getFriendsPK().getFriend());
                friends.put("friendLevel", "" + em.find(Player.class, f.getFriendsPK().getFriend()).getFurthestPlayedLevel());
                friends.put("friendScore", "" + em.find(Player.class, f.getFriendsPK().getFriend()).getAccumScore());
                friends.put("friendPicture", "" + em.find(Player.class, f.getFriendsPK().getFriend()).getPicture());
                friends.put("friendOnline", "" + em.find(Player.class, f.getFriendsPK().getFriend()).getIsOnline());
                friendsInfo.add(friends);
            }
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


        return friendsInfo;
    }

        //Find a friend belongs to a user by searching friend's name.
        private List<Map<String, String>> searchFriends(String userName, String friendName) {
        List<Map<String, String>> friendsInfo = new ArrayList<Map<String, String>>();

        try {
            //get context from context file.
            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            //this time get friends and fine by both user name and by friend name
            Query p = em.createNamedQuery("Friends.findByUserNameAndfriend").setParameter("userName", userName).setParameter("friendName", friendName);
            List<Friends> results = p.getResultList();
            for (Friends c : results) {
                Map<String, String> friends = new HashMap<String, String>();
                friends.put("friendName", c.getFriendsPK().getFriend());
                friends.put("friendLevel", "" + em.find(Player.class, c.getFriendsPK().getFriend()).getFurthestPlayedLevel());
                friends.put("friendScore", "" + em.find(Player.class, c.getFriendsPK().getFriend()).getAccumScore());
                friends.put("friendPicture", "" + em.find(Player.class, c.getFriendsPK().getFriend()).getPicture());
                friends.put("friendOnline", "" + em.find(Player.class, c.getFriendsPK().getFriend()).getIsOnline());
                friendsInfo.add(friends);
            }
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


        return friendsInfo;
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
